<?php

namespace app\admin\controller\shop;

use app\admin\model\ShopCate;
use app\admin\model\ShopStore;
use app\admin\model\UserBase;
use app\admin\service\CurlService;
use app\admin\traits\Curd;
use app\common\controller\AdminController;
use app\common\service\QRcodeService;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\db\Query;

/**
 * @author Fashion
 * @ControllerAnnotation(title="shop_store")
 */
class Store extends AdminController
{

    use Curd;

    protected $map_key;
    protected $allowModifyFields = [
        'brief', 'status', 'title', 'shop_sort'
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->map_key = 'JAZBZ-CXIK3-3AZ3G-3RJW4-IIQF3-FKFEX';
        $this->model = ShopStore::init();
        $this->assign('map_key', $this->map_key);
    }


    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParams();
            //关联时重复字段处理
            foreach ($where as &$condition) {
                if ($condition[0] == 'status') {
                    $condition[0] = env('DATABASE.PREFIX') . $this->model->getName() . '.status';
                }
            }
//            dd($where);
            $count = $this->model
                ->where($where)
                ->withJoin([
                    'cate',
                ], 'LEFT')
                ->count();
            $list = $this->model
                ->where($where)
                ->withJoin([
                    'cate' => ['id', 'title']
                ], 'LEFT')
//                ->with([
//                    'cate' => function ($query) {
//                        $query->field(['id', 'title']);
//                    }
//                ])
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data = [
                'code' => 0,
                'msg' => '',
                'count' => $count,
                'data' => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     * @param mixed $id
     * @return mixed
     */
    public function add($id = null)
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                'cate_id|店铺分类' => 'require',
                'title|分类名称' => 'require',
                'brief|店铺描述' => 'max:120',
//                'icon|分类图标' => 'require',
            ];
            $this->validate($post, $rule);
            try {
                $save = $this->model->save($post);
                UserBase::init()->bindStore((int)$post['bind_user'], $id);
            } catch (\Exception $e) {
                $this->error('保存失败，' . $e->getMessage());
            }
            if ($save) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        }
        $cate_list = ShopCate::init()->getCateList();
        unset($cate_list[0]);
        $this->assign([
            'id' => $id,
            'cate_list' => $cate_list
        ]);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->except(['__token__', 'file']);
            $rule = [
                'cate_id|店铺分类' => 'require',
                'title|分类名称' => 'require',
                'brief|店铺描述' => 'max:120',
//                'icon|分类图标' => 'require',
            ];
            $this->validate($post, $rule);
            try {
                $save = $row->save($post);
                UserBase::init()->bindStore((int)$post['bind_user'], (int)$id);
            } catch (\Exception $e) {
                $this->error('保存失败，' . $e->getMessage());
            }
            if ($save) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        }
        $cate_list = ShopCate::init()->getCateList();
        unset($cate_list[0]);
        $this->assign([
            'id' => $id,
            'row' => $row,
            'cate_list' => $cate_list
        ]);
        return $this->fetch();
    }


    /**
     * @NodeAnotation(title="删除")
     */
    public function delete()
    {
        $id = input("{$this->model->getPk()}", input('id'));
        $pk_name = $this->model->getPk();
        $row = $this->model->whereIn($pk_name, $id)->field([$pk_name])->select();
        $row->isEmpty() && $this->error('数据不存在');
        try {
            $save = $this->model->destroy(function ($query) use ($pk_name, $id) {
                $query->whereIn($pk_name, $id);
            });
        } catch (\Exception $e) {
            $this->error('删除失败' . $this->model->getLastSql());
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }


    //获取当前地址
    public function position()
    {
        $url = 'https://apis.map.qq.com/ws/location/v1/ip?key=' . $this->map_key;
        $header[] = "Content-Type:application/json;charset=UTF-8";
        $re = CurlService::init()->curl_get($url, $header);
        $this->success('获取成功', $re['result']);
    }

    /**
     * @NodeAnotation(title="手动生成二维码")
     */
    public function createQrcode()
    {
        //获取设备信息
//        "http://epay.zzmind.cn/admin/shop.store/index.html
        $id = input('id');
        $store_info = $this->model->find($id);
        $old_qrcode = $store_info->qrcode;
        //开始绘制二维码
        $_HTTP_REFERER = $this->request->server('HTTP_REFERER');
        $code = $this->request->domain() . '/api/p.html?m=' . $store_info->id;
        $res = QRcodeService::init()->png($code)->logo($store_info->shop_cover)->entry();
        if ($res && is_string($res)) {
            $store_info->qrcode = $res;
            $store_info->save();
            //删除上一张照片
            if ($old_qrcode) {
                $old_link = './' . substr($old_qrcode, strpos($old_qrcode, 'uploads'));
                unlink($old_link);
            }
            $this->success('二维码已生成');
        } else {
            $this->error('生成失败');
        }
    }


    /**
     * @NodeAnotation(title="批量导出二维码")
     * @author FashionJune
     */
    public function exportQrcode()
    {

        $map_store = [
            ['status' , '=' , 1],
            ['qrcode', '>', ''],
        ];
        $store_list = $this->model->where($map_store)->field(['id', 'title', 'qrcode'])->select();
        $zip = new \ZipArchive();
        $zipname = '店铺二维码.zip';
        if (file_exists($zipname)) {
            unlink($zipname);//删除之前的压缩包
        }
        $res = $zip->open($zipname, $zip::CREATE);
        if ($res) {
            foreach ($store_list as $store) {
                $qrcode_path = str_replace('https://epay.zzmind.cn/', './' , $store->qrcode);
                $zip->addFile($qrcode_path, $store->title . '.png');
            }
            $zip->close();
            header("Content-Type: application/zip");
            header("Content-Transfer-Encoding: Binary");
            header("Content-Length: " . filesize($zipname));
            header("Content-Disposition: attachment; filename=\"" . basename($zipname) . "\"");
            readfile($zipname);
            exit;
        }
    }

}